package com.young.monitor.service;

import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.*;

/**
 * @Author: Young
 * @CreateTime: 2025-01-14
 * @Description:
 * @Version: 1.0
 */
@Service
public class FileWatcherService {

    private final Path pathToWatch;

    public FileWatcherService() {
        // 设置要监听的目录路径
        this.pathToWatch = Paths.get("F:\\test");
    }

    public void startWatching() throws IOException, InterruptedException {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        pathToWatch.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

        System.out.println("开始监听目录: " + pathToWatch);
        while (true) {
            WatchKey key = watchService.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                Path fileName = (Path) event.context();
                System.out.println("事件类型: " + kind + ", 文件名: " + fileName);
                parseFile(fileName.toFile().getAbsolutePath());
            }
            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
    }

    private void parseFile(String filePath) {
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                // 按逗号分隔符拆分行内容
                String[] columns = line.split(",");
                if (columns.length == 4) {
                    String column1 = columns[0];
                    String column2 = columns[1];
                    String column3 = columns[2];
                    String column4 = columns[3];

                    // 打印或处理每一列的数据
                    System.out.println("Column 1: " + column1);
                    System.out.println("Column 2: " + column2);
                    System.out.println("Column 3: " + column3);
                    System.out.println("Column 4: " + column4);
                } else {
                    System.err.println("The file does not contain exactly 4 columns.");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
